package com.yongdin.minimalism.wifi;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.NetworkInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.util.Log;

import com.yongdin.minimalism.util.Utils;


/**
 * @ClassName: WfifReceiver
 * @Description: java类作用描述
 * @Author: luweiming
 * @CreateDate: 2020/3/24 15:12
 * @Version: 1.0
 */
public class WifiReceiver extends BroadcastReceiver {
    private static final String TAG = "wifiReceiver";

    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent.getAction().equals(WifiManager.RSSI_CHANGED_ACTION)) {
            Log.i(TAG, "wifi信号强度变化");
        }
        //wifi连接上与否
        if (intent.getAction().equals(WifiManager.NETWORK_STATE_CHANGED_ACTION)) {

            NetworkInfo info = intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);
            if (info.getState().equals(NetworkInfo.State.DISCONNECTED)) {
                Log.i(TAG, "wifi断开");
                if (null != callBack) {
                    callBack.onDisconnect();
                }
            } else if (info.getState().equals(NetworkInfo.State.CONNECTED)) {
                WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
                WifiInfo wifiInfo = wifiManager.getConnectionInfo();
                //获取当前wifi名称
                Log.i(TAG, "连接到网络 " + wifiInfo.getSSID());
                if (null != callBack) {
                    callBack.onConnected(wifiInfo.getSSID(), Utils.intToIp(wifiInfo.getIpAddress()));
                }
            }
        }
        //wifi打开与否
        if (intent.getAction().equals(WifiManager.WIFI_STATE_CHANGED_ACTION)) {
            int wifistate = intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE, WifiManager.WIFI_STATE_DISABLED);
            if (wifistate == WifiManager.WIFI_STATE_DISABLED) {
                Log.i(TAG, "系统关闭wifi");
                if (null != callBack) {
                    callBack.onClosed();
                }
            } else if (wifistate == WifiManager.WIFI_STATE_ENABLED) {
                Log.i(TAG, "系统开启wifi");
            }
        }
    }

    public WifiReceiver(IWifiCallBack callBack) {
        this.callBack = callBack;
    }

    private IWifiCallBack callBack;

    public interface IWifiCallBack {
        void onDisconnect();

        void onConnected(String ssid, String ip);

        void onClosed();
    }
}